﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace Dotnet.Utils.Utility.DrawingUtil
{
    public static class MatrixUtil
    {
        public static RectangleF Points2Rectangle(float x1, float y1, float x2, float y2)
        {
            return new RectangleF
            {
                X = Math.Min(x1, x2),
                Width = Math.Abs(x2 - x1),
                Y = Math.Min(y1, y2),
                Height = Math.Abs(y2 - y1)
            };
        }

        public static RectangleF ToRectangleF(Rectangle rect1)
        {
            return new RectangleF
            {
                X = rect1.X,
                Width = rect1.Width,
                Y = rect1.Y,
                Height = rect1.Height
            };
        }

        public static Rectangle ToRectangle(RectangleF rect1)
        {
            return new Rectangle
            {
                X = (int)rect1.X,
                Width = (int)rect1.Width,
                Y = (int)rect1.Y,
                Height = (int)rect1.Height
            };
        }

        public static RectangleF ApplyRect(RectangleF rect, Matrix transform)
        {
            RectangleF rectangleF = rect;
            PointF[] array = new PointF[]
            {
                new PointF(rectangleF.Left, rectangleF.Top),
                new PointF(rectangleF.Right, rectangleF.Bottom)
            };
            transform.TransformPoints(array);
            return Points2Rectangle(array[0].X, array[0].Y, array[1].X, array[1].Y);
        }

        public static RectangleF ApplyRect(Rectangle rect, Matrix transform)
        {
            RectangleF rectangleF = rect;
            PointF[] array = new PointF[]
            {
                new PointF(rectangleF.Left, rectangleF.Top),
                new PointF(rectangleF.Right, rectangleF.Bottom)
            };
            transform.TransformPoints(array);
            return Points2Rectangle(array[0].X, array[0].Y, array[1].X, array[1].Y);
        }

        public static Matrix InvertTrans(Matrix transform)
        {
            float[] elements = transform.Elements;
            Matrix matrix = new Matrix(elements[0], elements[1], elements[2], elements[3], elements[4], elements[5]);
            matrix.Invert();
            return matrix;
        }
    }
}